const express = require('express')
const router = express.Router()
const dateformat = require('dateformat')
const fs = require('fs')
const path = require('path')
const multer = require('multer')
const File = require('../Model/File')

let upload = multer({ dest: 'public/head/' }).single('headPhoto')
let uploadPage = multer({ dest: 'public/page/' }).single('pagePhoto')

function renameFileSync(file) {
  const date = dateformat('yyyymmdd')
  const oldFileName = path.join(__dirname, '../', file.path)
  const fileName = `${file.filename}_${date}.${file.originalname.split('.').pop()}`
  const filePath = path.join(__dirname, '../', file.destination, fileName)
  fs.renameSync(oldFileName, filePath)
  file.filename = fileName
  file.path = file.destination + fileName
  return file
}

router.post('/head', upload, function(req, res, next) {
  req.file.user = req.user._id
  req.username = req.user.username
  const file = renameFileSync(req.file)
  File.create(file, (err, doc) => {
    if (!err) {
      res.success(doc.path.toString())
    } else {
      res.error(500)
    }
  })
})
  .post('/page', uploadPage, function(req, res, next) {
    req.file.user = req.user._id
    const file = renameFileSync(req.file)
    File.create(file, (err, doc) => {
      if (!err) {
        res.success(doc.path.toString())
      } else {
        res.error(500)
      }
    })
  })

module.exports = router